package com.github.dtkavin.bgq.utils

import com.alibaba.fastjson.JSONObject
import org.slf4j.{Logger, LoggerFactory}
import redis.clients.jedis.Jedis

import scala.util.{Failure, Success, Try}

object RedisHelper {

  val logger: Logger = LoggerFactory.getLogger("RedisHelper")

  val REDIS_HOST = "bigdata-gw001.eq-sg-2.apus.com"
  val REDIS_PORT = 6379

  def push(key: String, value: String): Unit = {
    Try(new Jedis(REDIS_HOST, REDIS_PORT)).map {
      jedis =>
        try {
          jedis.lpush(key, value)
        } finally {
          jedis.close()
        }
    } match {
      case Success(_) => logger.info(s"$key:${value}写redis成功")
      case Failure(ex) => logger.error(s"$key:${value}写redis失败", ex)
    }
  }

  def push(key: String, valMap: Map[String, String]): Unit = {
    Try(new Jedis(REDIS_HOST, REDIS_PORT)).map {
      jedis =>

        val value = valMap.foldLeft(new JSONObject()) {
          case (old, (k, v)) =>
            old.put(k, v)
            old
        }.toString

        try {
          jedis.lpush(key, value)
        } finally {
          jedis.close()
        }
    } match {
      case Success(_) => logger.info(s"$key:${valMap}写redis成功")
      case Failure(ex) => logger.error(s"$key:${valMap}写redis失败", ex)
    }
  }
}
